var app = getApp();
import { config } from '../../../utils/config'
import util from '../../../utils/util'
import api from '../../../utils/api.js'
var WxParse = require('../../../utils/wxParse/wxParse.js');

// pages/pointsMall/pointsDetail/pointsDetail.js
Page({

    /**
     * Page initial data
     */
    data: {
        imgUrl: config.imgUrl,
        showTop: true,
        maskShow: false,
        num: 1,
        payBtn: true,
        temp: []

    },

    /**
     * Lifecycle function--Called when page load
     */
    onLoad: function (options) {
        let type = options.type;
        let id = options.id;
        this.setData({
            type,
            id
        })
        // 获取详情
        this.getProductDetails();

        // 获取剩余积分 
        this.accountPoints();

        this.isAuth();
    },
    isAuth() {
        let is_auth = wx.getStorageSync('is_auth');
        if (is_auth == true) {
            this.setData({
                is_auth
            })
        } else {
            this.setData({
                is_auth: false
            })
        }
    },
    likesClick() {
        this.setData({
            is_auth: true
        })
    },
    maskShow() {
        let exchangeCheck = this.exchangeCheck();
        if (exchangeCheck == false) {
            return;
        } else {
            this.setData({
                maskShow: true
            })
        }


    },
    getAdd() {
        let integralAddress = wx.getStorageSync('integralAddress');
        if (integralAddress) {
            this.setData({
                integralAddress
            })
        }
    },

    accountPoints() {
        util.getInfo(api.accountCoins, 'GET', {}, false).then(res => {
            this.setData({
                points: res.points, // 积分
                coins: res.coins  //歌豆
            })
        })
    },
    /*获取积分商城商品详情*/
    getProductDetails() {
        let that = this
        let data = {
            product_id: this.data.id
        }
        util.getInfo(api.integralGetDetail, 'GET', data).then(res => {
            // 评论
            res.reviews.list.forEach(item => {
                item.user.nickname.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
                if (item.user.nickname.length > 2) {
                    item.user.nickname = item.user.nickname.replace(/^(.).*(.)$/, "$1***$2")
                } else {
                    item.user.nickname = item.user.nickname.replace(/^(.).*$/, "$1***");
                }

            })

            this.setData(res);
            // 默认选中第一个
            let productAttr = res.productAttr;
            productAttr.forEach(item => {
                item.choose = item.specs_value[0];
                item.attr_value[0].check = true
            })
            // 截取图片
            that.cutShareImg(res.productInfo.image);




            // 匹配属性价格
            // 支付方式匹配
            let choose = [];
            productAttr.forEach(item => {
                if (item.choose) {
                    choose.push(item.choose)
                }
            })
            // 对选中属性排列组合 循环匹配
            this.combination(choose);
            // console.log('choose',choose)

            // 富文本编辑器转换  
            WxParse.wxParse('article', 'html', res.productInfo.details, that, 5);
            // 设置导航头
            wx.setNavigationBarTitle({
                title: res.productInfo.product_name,
            })
            this.setData({
                productAttr,
                payMethod: 0
            })
        })
    },
    /*支付选项点击*/
    selectPay(e) {
        let pay = e.currentTarget.dataset.pay
        let is_member = this.data.is_member;
        if (pay == 1) {
            if (is_member == 0) {
                wx.showModal({
                    title: '提示',
                    content: '您还不是会员，无法使用歌豆，是否成为会员？ ',
                    cancelText: '不用了',
                    confirmText: '成为会员',
                    confirmColor: '#ea5d56',
                    cancelColor: '#999999',
                    success(res) {
                        if (res.confirm) {
                            console.log('成为会员')
                            wx.navigateTo({
                                url: '/pages/vippromotion/vippromotion'
                            })
                        } else if (res.cancel) {
                            console.log('用户点击取消')
                        }
                    }
                })
            }
            if (is_member == 1) {
                this.setData({
                    payMethod: 1
                })
            }
        }
        if (pay == 0) {
            if (is_member == 1) {
                this.setData({
                    payMethod: 0
                })
            }
        }
    },
    /*获取地址*/
    getAddress() {
        wx.navigateTo({
            url: '/pages/allDizhi/allDizhi'
        })
    },

    /*切换选项*/
    changeAttr(e) {
        // 选择属性
        let pindex = e.currentTarget.dataset.pindex;
        let index = e.currentTarget.dataset.index;
        let productAttr = this.data.productAttr
        let attrObj = productAttr[pindex]['attr_value'][index]  //{attr: "M", check: false}
        productAttr[pindex]['attr_value'].forEach(item => {
            item.check = false
        });
        attrObj.check = !attrObj.check;
        let attr = this.data.attr;
        productAttr[pindex]['choose'] = attrObj.attr
        this.setData({
            productAttr: productAttr
        })

        // 支付方式匹配
        let choose = [];
        productAttr.forEach(item => {
            if (item.choose) {
                choose.push(item.choose)
            }
        })

        this.combination(choose);

        // choose = choose.substr(0, choose.length - 1)
        // console.log('choose',choose)
        // let productValue = this.data.productValue;
        // let productPay = productValue[choose];
        // console.log(productPay)
        // this.setData({
        //     productPay
        // })

    },

    combination(arr) {
        let temp = this.data.temp
        for (var i = 0; i < arr.length; i++) {
            // 插入第i个值
            temp.push(arr[i]);
            // 复制数组
            var copy = arr.slice();
            // 删除复制数组中的第i个值，用于递归
            copy.splice(i, 1);
            if (copy.length == 0) {
                // 如果复制数组长度为0了，则打印变量
                // console.log(arr);
                // console.log(temp);
                let tempStr = temp.toString();
                let productValue = this.data.productValue;

                for (const item in productValue) {
                    if (tempStr == item) {
                        this.setData({
                            productPay: productValue[tempStr],
                            temp: []
                        })
                        break;
                    }
                }

            } else {
                // 否则进行递归
                this.combination(copy);
            }
            // 递归完了之后删除最后一个元素，保证下一次插入的时候没有上一次的元素
            temp.pop();
        }

    },
    preventD() {
        return
    },
    /*立即兑换*/
    exchange() {

        let exchangeCheck = this.exchangeCheck();
        if (exchangeCheck == false) {
            return;
        }
        let address = wx.getStorageSync('integralAddress');
        let productPay = this.data.productPay;



        let payMethod = this.data.payMethod;
        // 支付方式 (1积分+现金 2积分+歌豆+现金)
        let pay_method;

        if (this.data.type == 2) {
            pay_method = 1
        } else {
            if (payMethod == 0) {
                pay_method = 1
            } else if (payMethod == 1) {
                pay_method = 2
            }
        }

        let data = {
            product_id: productPay.product_id,
            product_attr_unique: productPay.unique,
            suk: productPay.suk,
            count: this.data.num,
            address_id: address.id,
            pay_method: pay_method
        }
        util.getInfo(api.integralCreateorder, 'POST', data).then(res => {
            this.setData({
                order_no: res.order_no
            })
            this.payOrder();
        })
    },
    /*兑换判断*/
    exchangeCheck() {
        let integralAddress = this.data.integralAddress;
        if (!integralAddress) {
            util.showMsg('请选择收货地址');
            this.setData({
                maskShow: true
            })
            return false;
        } else {
            let city = integralAddress.city;
            let productArea = this.data.productInfo.shipping_area;
            if (productArea) {
                if (productArea.indexOf(city) < 0 || city.indexOf(productArea) < 0) {
                    util.showMsg('此地区不能购买');
                    this.setData({
                        maskShow: true
                    })
                    return false;
                }
            }

        }


        let payMethod = this.data.payMethod;
        let productPay = this.data.productPay;
        // console.log('payMethod',payMethod);
        if (payMethod == 1) {
            // vip歌豆 + vip积分 + vip现金
            if (this.data.points < productPay.vip_inte_price) {
                util.showMsg('积分不足');
                setTimeout(() => {
                    this.setData({
                        maskShow: true
                    })
                }, 800);

                return false;
            }

            if (this.data.coins < productPay.gebean_price) {

                util.showMsg('歌豆不足，请更换支付方式');
                setTimeout(() => {
                    this.setData({
                        maskShow: true
                    })
                }, 800);


                return false;
            }
        } else if (payMethod == 0) {
            // 积分 + 现金
            if (this.data.points < productPay.inte_price) {
                util.showMsg('积分不足');
                setTimeout(() => {
                    this.setData({
                        maskShow: true
                    })
                }, 800);

                return false;
            }
        }
    },


    /*支付*/
    payOrder() {
        let that = this;

        if (!this.data.payBtn) {
            return false
        } else {
            this.setData({
                payBtn: false
            })
        }

        let order_no = this.data.order_no;
        let data = {
            order_no
        }
        util.getInfo(api.integralPay, 'POST', data).then(res => {
            // 调起微信支付
            wx.requestPayment({
                'timeStamp': res.timeStamp,
                'nonceStr': res.nonceStr,
                'package': res.package,
                'signType': 'MD5',
                'paySign': res.paySign,
                'success': function (result) {
                    console.log('支付成功', result);

                    wx.navigateTo({
                        url: '/pages/pointsMall/paySuccess/paySuccess'
                    })

                },
                'fail': function (result) {

                    wx.navigateTo({
                        url: `/pages/pointsMall/paySuccess/paySuccess?order_no=${order_no}`
                    })
                    console.log('支付失败', result);
                    // reject(res)

                },
                'complete': function (result) {
                    that.payNotify(order_no);

                    that.setData({
                        payBtn: true
                    })
                }
            })
        })
    },
    payNotify() {
        util.getInfo(api.integralPayNotify, 'POST', { order_no: this.data.order_no }, false).then(res => {
            console.log('payNotify请求完成');
        })
    },
    toComments() {
        let id = this.data.id
        wx.navigateTo({
            url: '/pages/pointsMall/comments/comments?id=' + id
        })
    },
    closeMask() {
        this.setData({
            maskShow: false
        })
    },
    showMask() {
        this.setData({
            maskShow: true
        })
    },
    editNums(e) {
        let vageType = e.currentTarget.dataset.type;
        // console.log(vageType);
        if (vageType === 'add') {
            // console.log(this.data.num)
            this.setData({
                num: this.data.num + 1
            })
        }
        if (vageType === 'sub') {
            if (this.data.num > 1) {
                this.setData({
                    num: this.data.num - 1
                })
            }
        }
    },
    /**
     * Lifecycle function--Called when page show
     */
    onShow: function () {


        this.getAdd();
    },
    onPageScroll: function (e) {
        // console.log(e.scrollTop)
        if (e.scrollTop > 300) {
            this.setData({
                showTop: false
            })
        } else {
            this.setData({
                showTop: true
            })
        }
    },


    /**
     * Called when user click on the top right corner to share
     */
    onShareAppMessage: function () {
        var that = this;
        var url = '/pages/pointsMall/details/details?id=' + that.data.id;
        return {
            title: that.data.productInfo.product_name,
            imageUrl: that.data.shareimg,
            path: '/pages/index/index?GoTo=' + encodeURIComponent(url)
        }
    },
    cutShareImg: function (imgurl) {
        let that = this;
        wx.getImageInfo({
            src: that.data.productInfo.image,  // 这里填写网络图片路径 
            success: (res) => {
                console.log('res', res)
                let ctx = wx.createCanvasContext('canvas');
                let canvasW = 640, canvasH = res.height;
                if (res.width / res.height > 5 / 4) { // 长宽比大于5:4
                    canvasW = res.height * 5 / 4;
                }
                ctx.drawImage(res.path, (res.width - canvasW) / 2, 0, canvasW, canvasH, 0, 0, canvasW, canvasH)
                ctx.draw(false, () => {
                    wx.canvasToTempFilePath({
                        width: canvasW,
                        height: canvasH,
                        destWidth: canvasW,
                        destHeight: canvasH,
                        canvasId: 'canvas',
                        fileType: 'jpg',
                        success: (res) => {
                            //设置分享图片路径
                            that.setData({
                                shareimg: res.tempFilePath
                            });
                        }
                    })
                })
            }
        });
    },
})